﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using __ts.Core.Utilities;

namespace __ts.Core.Plugin
{
    /// <summary>
    /// 
    /// </summary>
    public class PluginManager
    {
        /// <summary>
        /// 
        /// </summary>
        private PluginManager() { }
        /// <summary>
        /// 
        /// </summary>
        public static PluginManager GetInstance
        {
            get
            {
                if (pm == null)
                    pm = new PluginManager();
                return pm;
            }
        }
        private static PluginManager pm = null;
        /// <summary>
        /// 
        /// </summary>
        private ManualResetEvent[] m_ResetEvents;
        /// <summary>
        /// 
        /// </summary>
        public void init()
        {
            if (_plugins != null && _plugins.Count > 0)
            {
                IDictionaryEnumerator enumerator = _plugins.GetEnumerator();
                while (enumerator.MoveNext())
                {
                    ((PluginDomain)enumerator.Value).Unload();
                }
                _plugins.Clear();
            }
            _plugins = new Dictionary<string, PluginDomain>();

            FileInfo[] fs = new DirectoryInfo(PluginsDirectory).GetFiles("*.dll", SearchOption.AllDirectories);
            if (fs != null && fs.Length > 0)
            {
                m_ResetEvents = new ManualResetEvent[fs.Length];
                for (int i = 0; i < fs.Length; i++)
                {
                    m_ResetEvents[i] = new ManualResetEvent(false);
                    ThreadPool.QueueUserWorkItem(new WaitCallback(_Load), new List<string>() { i.ToString(), fs[i].FullName });
                }
                WaitHandle.WaitAll(m_ResetEvents);
            }
        }
        /// <summary>
        /// 加载插件的域集合
        /// </summary>
        private Dictionary<string, PluginDomain> _plugins;
        /// <summary>
        /// 插件存放的目录
        /// </summary>
        public string PluginsDirectory { get { return Util.RootPath + "\\Plugins"; } }
        /// <summary>
        /// 配置文件存放的目录
        /// </summary>
        public string ConfigsDirectory { get { return Util.RootPath + "\\Configs"; } }
        /// <summary>
        /// 提供服务的端口
        /// </summary>
        public List<int> Ports
        {
            get
            {
                if (_ports == null || _ports.Count < 1)
                {
                    _ports = new List<int>();
                    string[] files = Directory.GetFiles(ConfigsDirectory, "*.xml", SearchOption.TopDirectoryOnly);
                    if (files.Length > 0)
                    {
                        foreach (string file in files)
                        {
                            int port = 0;
                            if (int.TryParse(Path.GetFileNameWithoutExtension(file), out port) && port > 0)
                            {
                                _ports.Add(port);
                            }
                        }
                    }
                }
                return _ports;
            }
        }
        private List<int> _ports = null;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pluginKey"></param>
        /// <returns></returns>
        public PluginDomain GetPluginDomain(string pluginKey)
        {
            if (_plugins.ContainsKey(pluginKey))
                return _plugins[pluginKey] as PluginDomain;
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        public Dictionary<string, PluginDomain> Plugins
        {
            get { return _plugins; }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="state"></param>
        private void _Load(Object state)
        {
            List<string> obj = state as List<string>;
            string assemblyPath = obj[1];

            // 检验命名是否规范
            if (Regex.IsMatch(Path.GetFileNameWithoutExtension(assemblyPath), @"^.+(?:_\d){3}$"))
            {
                PluginDomain domain = new PluginDomain(assemblyPath);
                IPlugin p = domain.GetPlugin();
                if (p != null)
                {
                    p.Host();
                    p.HostDate = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
                    _plugins.Add(p.Key, domain);
                }
            }
            m_ResetEvents[Convert.ToInt32(obj[0])].Set();
        }
    }
}
